function loglik = llf_restat(y,params,init_V,gainvector,k);
%this create the log likelihood for the following model.
%   x(t+1) = A*x(t) + w(t),  w ~ N(0, Q),  x(0) ~ N(init_x, init_V)
%   y(t)   = C*x(t) + v(t),  v ~ N(0, R)

% state(t) = T*state(t-1) + err1(t), Eerr1(t)*err1(t)'=Q
% data(t) = Z*state(t) + err2(t), Eerr2(t)*err2(t)'=H

%x(t) is a vector
%e perm  
%e temp
%Phi risk prem. 
%e perm  is a random walk 
%e temp is an AR(1) with persistence defined by A(2,2)
%Phi risk prem is an AR(1) with persistence defined by A(3,3)
% k is the number of periods ahead is the futures quote for delivery. 

% The data in y is the Delta Spot and Futures - Spot 

if nargin < 4;
    gainvector = [];
end
if nargin == 2;
	init_V = [];
end 


if length(params) ~= 5;
    error('wrong model');
end

rho_riskprem 	= params(1);
rho_temp 		= params(2);
sigperm 		= abs(params(3));
sigtemp 	    = abs(params(4));
sigxi 			= abs(params(5));




% init_x = [muc 1*mean(y(1:20)) 0*mean(y(1:20))]';
init_x = [0 0 0 0 0 0]';

if isempty(init_V);
init_V = diag([sigperm  sigtemp./sqrt(1-rho_temp^2)   sigxi./sqrt(1-rho_riskprem ^2)   sigperm  sigtemp./sqrt(1-rho_temp^2)  sigxi./sqrt(1-rho_riskprem ^2) ].^2); 

    init_V(2,5)  = rho_temp*(sigtemp^2)./(1-rho_temp^2);
    init_V(5,2) = rho_temp*(sigtemp^2)./(1-rho_temp^2);
    init_V(3,6) = rho_riskprem *(sigxi^2)./(1-rho_riskprem^2);
    init_V(6,3) = rho_riskprem *(sigxi^2)./(1-rho_riskprem^2);
 
end


% The A matrix makes the curent state equal to the lagged state
    
A = zeros(6,6);
A(1,1) = 1;
A(2,2) = rho_temp;
A(3,3) = rho_riskprem;
A(4,1) =    1;
A(5,2) =    1;
A(6,3) = 1;

 

Q = diag([sigperm sigtemp sigxi 0 0 0].^2);
R = 0^2;
C = [1 1 0 -1 -1 0 ; 0 rho_temp^k-1 1 0 0 0];

%What does this mean. 
%DPt = eperm (t)- eperm(t-1) + etemp (T) - etemp(t-1) 
% Ft-St = 0 + (rho_temp^k-1)*etemp(t) +   Risk Premium


if isempty(gainvector)
    [loglik] = mykalman(y,A,C,Q,R,init_x,init_V,0);
else
    [loglik] = mykalmanwithgain(y,A,C,Q,R,init_x,init_V,0,gainvector);
end

loglik = -1*loglik;

